package com.ronri.ams.sample;

/**
 * 文件：ams.java
 * 包名：com.ronri.ams.sample;
 * 说明：
 * 作者：MS During
 * 日期：2017/6/20
 * 历史：
 */

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.baidu.mapapi.model.LatLng;
import com.cz.nongyetongv5.R;
import com.cz.nongyetongv5.application.InitApplication;
import com.ronri.ams.SystemEnvironmental;
import com.ronri.ams.bean.entList;
import com.ronri.common.UrlEncode;
import com.ronri.common.WaitDialog;
import com.ronri.db.RemoteDataService;
import com.zhy.autolayout.utils.AutoUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.cz.nongyetongv5.application.InitApplication.gSampleInfo;


/****
 * 列表
 */
public class fragmentList extends Fragment {

    private Context mContext = null;
    private ListView mListView = null;
    private List<MapItem> mItems = new ArrayList<>();
    private IRemoteMapData OnRemoteData = null;
    private Button mbtUP;
    private Button mbtDW;
    public int mPageIndex = 1;

    public int mTotalPages = 1;
public String searchKey;

    public void setIRemoteMapData(IRemoteMapData callback) {
        OnRemoteData = callback;
    }

    public void setSearchKey(String searchKey){
        this.searchKey=searchKey;
    }


    /***
     * 刷新列表数据
     * @param items
     */
    public void RefreshData(List<MapItem> items) {

        mItems = items;
        List<Map<String, Object>> listems = new ArrayList<Map<String, Object>>();
        for (MapItem item : mItems) {
            Map<String, Object> listem = new HashMap<String, Object>();
            listem.put("vtitle", item.mTtitle);
            listem.put("vhumen", item.mHumen);
            listem.put("vtelphone", item.mTelphone);
            listems.add(listem);
        }

        mListView.setAdapter(new ListAdapter());

        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                OnRemoteData.Seleced(mItems.get(i));
            }
        });
    }

    /****
     * 列表适配器
     */
    class ListAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return mItems.size();
        }

        @Override
        public Object getItem(int i) {
            return mItems.get(i);
        }

        @Override
        public long getItemId(int i) {
            return i;
        }

        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {

            if (view == null) {
                view = LayoutInflater.from(mContext).inflate(R.layout.venterprise_info, viewGroup, false);

                view.setTag(mItems.get(i));

                //对于listview，注意添加这一行，即可在item上使用高度
                AutoUtils.autoSize(view);
            }
            TextView title = (TextView) view.findViewById(R.id.vtitle);
            TextView humen = (TextView) view.findViewById(R.id.vhumen);
            TextView telphone = (TextView) view.findViewById(R.id.vtelphone);

            title.setText(mItems.get(i).mTtitle);
            humen.setText(mItems.get(i).mHumen);
            telphone.setText(mItems.get(i).mTelphone);

            return view;
        }
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View returnView = inflater.inflate(R.layout.enterprise_map_list, container, false);
        mContext = getActivity();
        Log.i("aaa", "fragmentList");

        getRemotePageData(mPageIndex,"");

        // 获取列表
        mListView = (ListView) returnView.findViewById(R.id.list);

        mbtUP = (Button) returnView.findViewById(R.id.btnPageUp);
        mbtDW = (Button) returnView.findViewById(R.id.btnPageDown);

        mbtUP.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //上一页
//                if (OnRemoteData != null) {
//                    if (mPageIndex > 1) {
//                                                OnRemoteData.GetPageData(mPageIndex --);
//                    }
//                }

                Log.i("test","mPageIndex-->"+mPageIndex);

                if(mPageIndex>1){
                    mPageIndex--;
                    getRemotePageData(mPageIndex,searchKey);
                }else if(mPageIndex==1){
                    Toast.makeText(mContext,"已是第一页", Toast.LENGTH_SHORT).show();
                }
            }
        });

        mbtDW.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //下一页
                if(mPageIndex < mTotalPages){
                    mPageIndex++;
                    getRemotePageData(mPageIndex,searchKey);
                }else{
                    Toast.makeText(mContext,"没有更多数据", Toast.LENGTH_SHORT).show();
                }
//                if (OnRemoteData != null) {
//                    if (mPageIndex < mTotalPages) {
//                        OnRemoteData.GetPageData(mPageIndex++);
//                    }
//
//                }
            }
        });

        if (OnRemoteData != null) {
            mItems = OnRemoteData.GetItemList();
            RefreshData(mItems);
        }

        return returnView;
    }

    /***
     * 获取数据
     * @param pageindex
     */
    public void getRemotePageData(int pageindex,String key) {
        RemoteDataService remoteDataService = new RemoteDataService();

        // 获取远程地址
        String szRemoteAddress = "http://120.55.93.238:8080/ams/api/entList.json";
        Map<String, Object> mParam = new HashMap<String, Object>();

        try {
            mParam.put("addFrom", 1);
            mParam.put("addMark", "android");
            mParam.put("page", pageindex);
            mParam.put("pageSize", 10);
            mParam.put("region_code", gSampleInfo.getSample_area());
            mParam.put("ent_name", key);

        } catch (Exception ex) {

        }
        Log.i("test", "mParam2-->" + mParam.toString());
        // 获取远程数据
        remoteDataService.getRemoteData(szRemoteAddress,
                UrlEncode.getUrlParamsByMap(mParam, false),
                InitApplication.SystemConfig.getModule().getTdetail().getMethod(),
                new RemoteDataService.OnRemoteDataEvent() {
                    // 返回结果
                    @Override
                    public void OnResultEvent(String szString) {
//                        Log.i("test", "szString-->" + szString);
                        if (szString.isEmpty())
                            return;

                        try {
                            entList entBean = JSON.parseObject(szString, entList.class);

                            if (entBean.isSuccess()) {
                                int total = entBean.getData().getTotal();
                                mItems = new ArrayList<MapItem>();

                                for (entList.DataBean.RowsBean iTem : entBean.getData().getRows()) {
                                    // 添加Marker点
                                    LatLng locate = new LatLng(iTem.getLatitude(), iTem.getLongitude());

                                    MapItem myitem = new MapItem(locate);

                                    myitem.mTtitle = iTem.getName();
                                    myitem.mHumen = iTem.getCharge();
                                    myitem.mRegionCode = iTem.getRegion();
                                    myitem.mTelphone = iTem.getTel();
                                    myitem.mAddress = iTem.getAddress();
                                    myitem.mId = iTem.getId();

                                    mItems.add(myitem);
                                }


                                RefreshData(mItems);
                                mTotalPages = total;

                            }
                        } catch (Exception ex) {
                            ex.printStackTrace();
                        }
                    }

                    // 状态控制，是否显示加载过程
                    @Override
                    public void OnRuningState(int nStatus) {
                        if (nStatus == SystemEnvironmental.StartGetDataFromServer) {
                            WaitDialog.ShowDialog(getActivity(), "请稍后...");
                        } else {
                            WaitDialog.HideDialog();
                        }
                    }

                    @Override
                    public String OnGetCustomParam() {
                        return null;
                    }
                }
        );
    }
}
